#!/usr/bin/env python
#Copyright 2009 Erik Tollerud
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys,os,glob
from subprocess import Popen
from optparse import OptionParser
from astropysics import version,publication


vstr = '%prog '+version.version
parser = OptionParser(usage='%prog [options] texfile format',version=vstr)
parser.description="""Prepares a LaTeX papers for a variety of different
publication locations. Currently supported format: 'arxiv'(prepares publication
for posting to arXiv.org), 'apj'(prepares publication for submission to the
Astrophysical Journal)
"""
parser.add_option("-d", "--directory", dest="directory",metavar="FILE",default='',
                  help="Specifies a directory for the files to be published.")
parser.add_option("-q", "--quiet",action="store_true", dest="quiet",
                  default=False,help="Supresses messages about actions taken.")
parser.add_option("-w", "--overwrite",action="store_true", dest="overwrite", 
                  default=False,help="Overwrite the directory instead of making a new one.")
parser.add_option("-c", "--compile",action="store_true", dest="compile", 
                  default=False,help="Attempt to compile using latex and possibly bibtex.")
parser.add_option("-f", "--figure-exts", dest="figexts",metavar="FIGEXTS",default='eps,pdf',
                  help="Specifies filename extensions to copy for figures.")

ops, args = parser.parse_args()

if len(args) != 2:
    parser.print_usage()
    sys.exit(1)
texfn,fmt = args

kwargs = dict(overwritedir=ops.overwrite,verbose=not ops.quiet)
if ops.directory != '':
    kwargs['newdir'] = ops.directory
if ops.figexts is not None:
    kwargs['figexts'] = ops.figexts.split(',')
    
publication.print_warnings = True

if fmt == 'arxiv':
    if not ops.quiet:
        print 'Preparing for arXiv publication'
    f,dir = publication.prep_for_arxiv_pub(texfn,**kwargs)
elif fmt == 'apj':
    if not ops.quiet:
        print 'Preparing for ApJ publication'
    f,dir = publication.prep_for_apj_pub(texfn,**kwargs)
else:
    print 'Unrecognized format "'+fmt+'", exiting with no action'

if ops.compile:
    def ecode_check(ecode,prog='latex'):
        if  ecode!=0:
            print prog,'failed with exit code',ecode,'... aborting compilation!'
            sys.exit(ecode)
    
    cwd = os.path.join(os.path.abspath('.'),dir)
    if not ops.quiet:
        print 'Compiling file ',os.path.join(cwd,f.lastsavefn)
    
    texfn = os.path.split(f.lastsavefn)[-1]
    bibs = f.visit(lambda n:n.reqargs[0] if isinstance(n,publication.Command) and n.name=='bibliography' else None)
    bibfn = os.path.join(cwd,bibs[0]+'.bib')
    
    if os.path.exists(bibfn):
        ecode_check(Popen(['latex',texfn],executable='latex',cwd=cwd).wait())
        ecode_check(Popen(['bibtex',texfn.replace('.tex','')],executable='bibtex',cwd=cwd).wait(),'bibtex')
    ecode_check(Popen(['latex',texfn],executable='latex',cwd=cwd).wait())
    ecode_check(Popen(['latex',texfn],executable='latex',cwd=cwd).wait())
    ecode_check(Popen(['latex',texfn],executable='latex',cwd=cwd).wait())
    
    